package edu.unr.cater.npap.client.scaffold.ui;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.SpanElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.user.client.ui.Widget;

import edu.unr.cater.npap.client.AuthService;
import edu.unr.cater.npap.client.AuthServiceAsync;
import edu.unr.cater.npap.client.scaffold.CustomizedDesktopLoginShell;

/**
 * A simple widget which displays info about the user and a logout link.
 */
public class LoginWidget extends Composite {
	
	interface Binder extends UiBinder<Widget, LoginWidget> {
	}

	private static final Binder BINDER = GWT.create(Binder.class);
	private CustomizedDesktopLoginShell loginShell;

	@UiField SpanElement name;
	@UiField Anchor logoutLink;

	public LoginWidget() {
		initWidget(BINDER.createAndBindUi(this));
	}

	public void setUserName(String userName) {
		name.setInnerText(userName);
	}

	public void setLogoutUrl(String url) {
		logoutLink.setHref(url);
	}

	/**
	 * Squelch clicks of the logout link if no href has been set.
	 */
	@UiHandler("logoutLink")
	void handleClick(ClickEvent e) {
		AuthServiceAsync authService = GWT.create(AuthService.class);

		authService.logOut(
				new AsyncCallback<Boolean>() {

					@Override
					public void onSuccess(Boolean result) {
						// TODO Auto-generated method stub
						if (result)
						{
//							Window.Location.reload();
//							CustomizedDesktopLoginShell loginShell=new CustomizedDesktopLoginShell();
							RootLayoutPanel.get().clear();
							loginShell.loginBox.setText("");
							loginShell.passwordBox.setText("");
							RootLayoutPanel.get().add(loginShell);
							setUserName("Not signed in");
						// Window.Location.reload();
						}							
						else
							Window.alert("Failed to logout!");
					}

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						Window.alert("Remote Procedure Call - Failure");

					}
				});
		if ("".equals(logoutLink.getHref())) {
			e.stopPropagation();
		}
	}

	/**
	 * @return the loginShell
	 */
	public CustomizedDesktopLoginShell getLoginShell() {
		return loginShell;
	}

	/**
	 * @param loginShell the loginShell to set
	 */
	public void setLoginShell(CustomizedDesktopLoginShell loginShell) {
		this.loginShell = loginShell;
	}
}
